<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <template v-if="formData.id != null">
        <el-alert title="当前租住位置" type="info" effect="dark" :closable="false" />
        <el-row>
          <el-col :span="12">
            <el-form-item label="租客姓名" prop="rentUserId">
              {{ formData.rentUserName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前地址">
              {{ formData.rentAddrName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="rentRoomBeforeRespVo && rentRoomBeforeRespVo.existsOldRoomMeter">
          <el-col :span="12">
            <el-form-item label="抄表时间">
              {{ formatDate(rentRoomBeforeRespVo.oldRoomMeter.lastConnecttime) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电表余额">
              {{ rentRoomBeforeRespVo.oldRoomMeter.lastBalance }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-alert
          title="移动到如下"
          type="error"
          effect="dark"
          :closable="false"
          style="margin-bottom: 10px"
        />
        <el-form-item label="房屋地址" prop="houseId">
          <el-select
            v-model="formData.houseId"
            style="width: 100%"
            filterable
            remote
            @change="houseSelClick"
            placeholder="请输入房屋关键词"
            :remote-method="remoteHouseMethod"
          >
            <el-option
              v-for="(item, index) in houseList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间地址" prop="roomId">
          <el-select
            v-model="formData.roomId"
            style="width: 100%"
            filterable
            remote
            @change="roomSelClick"
            placeholder="请输入房间"
            :remote-method="remoteRoomMethod"
          >
            <el-option
              v-for="(item, index) in roomList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-row v-if="rentRoomBeforeRespVo && rentRoomBeforeRespVo.existsOldRoomMeter">
          <el-col :span="12">
            <el-form-item label="抄表时间">
              {{ formatDate(rentRoomBeforeRespVo.newRoomMeter.lastConnecttime) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电表余额">
              {{ rentRoomBeforeRespVo.newRoomMeter.lastBalance }}
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 实现三类数据操作-->
        <el-form-item
          label="清除余额"
          v-if="rentRoomBeforeRespVo && rentRoomBeforeRespVo.existsOldRoomMeter"
        >
          <el-switch
            v-model="formData.clearOldMeterBalanceFlag"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="true"
            :inactive-value="false"
          />
          清除<span style="color: red">原</span>房间电表余额
        </el-form-item>
        <el-form-item
          label="清除余额"
          v-if="rentRoomBeforeRespVo && rentRoomBeforeRespVo.existsNewRoomMeter"
        >
          <el-switch
            v-model="formData.clearNewMeterBalanceFlag"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="true"
            :inactive-value="false"
          />
          清除<span style="color: red">新</span>房间电表余额
        </el-form-item>
        <el-form-item
          label="余额迁移"
          v-if="
            rentRoomBeforeRespVo &&
            rentRoomBeforeRespVo.existsOldRoomMeter &&
            rentRoomBeforeRespVo.existsNewRoomMeter
          "
        >
          <el-switch
            v-model="formData.moveBalanceFromOldToNewFlag"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="true"
            :inactive-value="false"
          />
          将原房间电表余额移动到新房间电表中
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="租客姓名" prop="rentUserId">
          <el-select
            v-model="formData.rentUserId"
            style="width: 100%"
            filterable
            remote
            @change="memberUserSelClick"
            placeholder="请输入租客姓名"
            :remote-method="remoteMemberUserSearch"
          >
            <el-option
              v-for="(item, index) in searchMemberUserList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋地址" prop="houseId">
          <el-select
            v-model="formData.houseId"
            style="width: 100%"
            filterable
            remote
            @change="houseSelClick"
            placeholder="请输入房屋关键词"
            :remote-method="remoteHouseMethod"
          >
            <el-option
              v-for="(item, index) in houseList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间地址" prop="roomId">
          <el-select
            v-model="formData.roomId"
            style="width: 100%"
            filterable
            remote
            @change="roomSelClick"
            placeholder="请输入房间"
            :remote-method="remoteRoomMethod"
          >
            <el-option
              v-for="(item, index) in roomList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm" :disabled="!canSubmit">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { formatDate } from '@/utils/formatTime'
import * as RoomRentApi from '@/api/zwsj/roomRent'
import { getMemberUserPageBySearch } from '@/api/member/user/index'
import { getHousesByManagerForSearch, getRoomsByHouseIdForSearch } from '@/api/zwsj/houseRoom'

defineOptions({ name: 'RoomRentForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref()
const oldRoomId = ref()
const canSubmit = ref(false) //是否可以提交

const rentRoomBeforeRespVo = ref()

const formRules = reactive({
  houseId: [
    {
      required: true,
      message: '房屋地址不能为空',
      trigger: 'blur'
    }
  ],
  roomId: [
    {
      required: true,
      message: '房间地址不能为空',
      trigger: 'blur'
    }
  ],
  rentUserId: [
    {
      required: true,
      message: '租客不能为空',
      trigger: 'blur'
    }
  ]
})

const formRef = ref() // 表单 Ref
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  resetCheck()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      if (type === 'update') {
        formData.value = await RoomRentApi.getRoomRent(id)
        oldRoomId.value = formData.value.roomId
        //重现
        formData.value.houseId = undefined
        formData.value.roomId = undefined
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    formData.value.newRoomId = formData.value.roomId
    const data = formData.value as unknown as RoomRentApi.RoomRentVo
    if (formType.value === 'create') {
      await RoomRentApi.createRoomRent(data)
      message.success(t('common.createSuccess'))
    } else {
      await RoomRentApi.replaceRoom(data)
      message.success('更新租住地址成功')
    }

    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    commId: undefined,
    houseId: undefined,
    roomId: undefined,
    newRoomId: undefined,
    rentAddrName: undefined,
    rentUserId: undefined,
    rentUserName: undefined,

    oldRoomMeterId: undefined,
    newRoomMeterId: undefined,
    clearOldMeterBalanceFlag: false,
    clearNewMeterBalanceFlag: false,
    moveBalanceFromOldToNewFlag: false
  }
  formRef.value?.resetFields()
}

//查询房屋地址
const houseList = ref([])
const remoteHouseMethod = (v) => {
  if (v !== '') {
    if (v.length < 2) {
      message.notifyError('房屋地址关键字长度必须在 2 个字以上（包括2个字）')
      return false
    }
    getHousesByManagerForSearch({
      keyWord: v,
      pageNo: 1,
      pageSize: 50
    }).then((data) => {
      houseList.value = data.list
    })
  } else {
    houseList.value.length = 0
  }
}

//查询房间地址
const roomList = ref([])
const remoteRoomMethod = (v) => {
  let houseId = formData.value.houseId || ''
  if (houseId === '') {
    message.notifyError('请先定位房屋信息')
    return false
  }
  if (v !== '') {
    if (v.length < 2) {
      // message.notifyError('关键字长度必须在 2 个字节以上（包括2个字节）')
      return false
    }
    canSubmit.value = false

    getRoomsByHouseIdForSearch({
      houseId: houseId,
      keyWord: v,
      pageNo: 1,
      pageSize: 100
    }).then((data) => {
      roomList.value = data.list
    })
  } else {
    roomList.value.length = 0
  }
}
//房屋选择，联动房间
const houseSelClick = (v) => {
  formData.value.roomId = undefined
}

const resetCheck = () => {
  rentRoomBeforeRespVo.value = {
    checkSuccess: false,
    existsOldRoomMeter: false,
    oldRoomMeter: {
      id: undefined
    },
    existsNewRoomMeter: false,
    newRoomMeter: {
      id: undefined
    }
  }
}

//房间选择
const roomSelClick = async (v) => {
  if(formData.value.id != null){
      canSubmit.value = false
      //将按钮变成灰色，同时查询目标房间电表相关信息
      let roomId = v || null
      if (roomId == oldRoomId.value) {
        message.error('目标房间不能与原房间相同')
        return false
      }

      formData.value.oldRoomMeterId = undefined
      formData.value.newRoomMeterId = undefined
      //message.notifySuccess('对房间电表抄表中，请稍等')

      rentRoomBeforeRespVo.value = await RoomRentApi.beforeReplaceRentRoomCheck({
        oldRoomId: oldRoomId.value,
        newRoomId: roomId
      })

      if(rentRoomBeforeRespVo.value.oldRoomMeter != null){
        formData.value.oldRoomMeterId = rentRoomBeforeRespVo.value.oldRoomMeter.id
      }
      
      if(rentRoomBeforeRespVo.value.newRoomMeter != null){
        formData.value.newRoomMeterId = rentRoomBeforeRespVo.value.newRoomMeter.id
      }
      canSubmit.value = true
      console.info("123")
  }else{
      canSubmit.value = true
  }
}

//查询租客信息
const searchMemberUserList = ref([])
const remoteMemberUserSearch = (v) => {
  v = v || ''
  if (v !== '') {
    if (v.length < 2) {
      message.notifyError('关键字长度必须在 2 个字节以上（包括2个字节）')
      return false
    }

    getMemberUserPageBySearch({
      keyWord: v,
      pageNo: 1,
      pageSize: 50
    }).then((data) => {
      searchMemberUserList.value = data.list
      searchMemberUserList.value.forEach((item) => {
        item.name = item.nickname
      })
    })
  } else {
    searchMemberUserList.value.length = 0
  }
}
//人员选择
const memberUserSelClick = (v) => {
  searchMemberUserList.value.forEach((item) => {
    if (item.id == v) {
      formData.value.rentUserName = item.name || ''
    }
  })
}
</script>
